package com.innovation.ic.b1b.monitor.base.handler;

import com.innovation.ic.b1b.framework.manager.SftpChannelManager;
import com.innovation.ic.b1b.monitor.base.mapper.LogMapper;
import com.innovation.ic.b1b.monitor.base.mapper.LogMonitorJobMapper;
import com.innovation.ic.b1b.monitor.base.model.ApiAvailableJob;
import com.innovation.ic.b1b.monitor.base.model.Log;
import com.innovation.ic.b1b.monitor.base.model.LogMonitorJob;
import com.innovation.ic.b1b.monitor.base.pojo.constant.JobDataMapConstant;
import com.jcraft.jsch.SftpException;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Author myq
 * @Date 2023/5/10 16:18
 * @Version 1.0
 * @Description 日志任务处理类
 */
@Component
@Slf4j
public class LogMonitorJobHandler extends QuartzJobBean {

    @Resource
    private LogMonitorJobMapper logMonitorJobMapper;

    @Resource
    private LogMapper logMapper;


    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("****************日志监控任务开始执行*****************");
        JobDataMap jobDataMap = context.getMergedJobDataMap();
        int id = jobDataMap.getInt(JobDataMapConstant.ID);
        LogMonitorJob logMonitorJob = logMonitorJobMapper.selectById(id);
        Assert.isNull(logMonitorJob, "日志监控数据异常：[{}]" + id);
        // 系统日志信息
        Log logInfo = logMapper.selectById(logMonitorJob.getLogId());
        try {
            getErrorLogByMatcher(logInfo.getIp(), logInfo.getPort(), logInfo.getUsername(), logInfo.getPassword(), logInfo.getFileRegularExpression());
        } catch (Exception e) {
            throw new RuntimeException("");
        }

        log.info("****************日志监控任务结束执行*****************");
    }

    /**
     * @param host
     * @param port
     * @param username
     * @param pass
     * @param dir
     * @Description: 通过正则获取异常日志
     * @Author: myq
     * @Date: 2023/5/10 16:37
     */
    private void getErrorLogByMatcher(String host, int port, String username, String pass, String dir) throws SftpException, IOException {
        SftpChannelManager sftpChannelManager = new SftpChannelManager(username, pass, host, port);
        List<String> fileList = sftpChannelManager.lsFile(sftpChannelManager, dir, new ArrayList<String>());
        String today = LocalDate.now().toString();
        // 保留当日的日志
        Set<String> stringSet = fileList.stream().filter(e -> e.contains(today)).collect(Collectors.toSet());
        // 保留当日索引最大的日志
        Map<String, Integer> mapByIndexMax = new HashMap<>();
        int min = -1;
        for (String f : stringSet) {
            int s = f.indexOf(".");
            int e = f.lastIndexOf(".");
            if (s != -1 && s > e) {
                int fix = Integer.parseInt(f.substring(f.indexOf(".") + 1, f.lastIndexOf(".")));
                if (fix > min) {
                    mapByIndexMax.put(f, fix);
                    min = fix;
                }
            } else {
                mapByIndexMax.put(f, 0);
            }
        }

        String absFile = fileList.get(0);
        int index = absFile.lastIndexOf("/");
        String dirPath = "./temp/";
        File file = new File(dirPath);
        if (!file.exists())
            file.mkdirs();
        String localFile = dirPath + absFile.substring(index + 1);
        sftpChannelManager.download(sftpChannelManager.getChannelSftp(), absFile, localFile);

        File f = new File(localFile);
        BufferedReader bs = new BufferedReader(new InputStreamReader(Files.newInputStream(f.toPath())));
        while (bs.ready()) {
            String s = bs.readLine();
            String p = LocalDate.now().toString();
            Pattern compile = Pattern.compile("(" + p + ").+(WARN).+");
            Matcher matcher = compile.matcher(s);
            while (matcher.find()) {
                System.out.println(matcher.group());
            }
        }
        sftpChannelManager.closeSession();
    }

    class Task extends Thread{

        @Override
        public void run() {
            super.run();
        }
    }
}
